package com.liang.four;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import utils.RabbitmqUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: XIAOLIANG
 * Date: 2021/6/18
 * Time: 0:33
 * Description:
 */
public class ConsumerMessage extends Thread{

    private static final String QUEUE_NAME = "confirm_queue2";

    private String name;


    public ConsumerMessage(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            work();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public void work() throws IOException, TimeoutException {


        Channel channel = RabbitmqUtil.getChannel();

//        channel.basicQos(0);


        channel.basicConsume(QUEUE_NAME, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {

                System.out.println(name+"消费了消息:"+ new String(message.getBody()));
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                System.out.println(name+"取消了 消费");
            }
        });



    }



    public static void main(String[] args) throws IOException, TimeoutException {

        ConsumerMessage a = new ConsumerMessage("A");
        ConsumerMessage b = new ConsumerMessage("B");
        b.start();
        a.start();



    }

}